<template>
  <div id="uploadImg">
    <div v-for="(item, index) in uploadedImgList" :key="index" class="img-box">
      <i class="icon el-icon-check"></i>
      <i class="icon del el-icon-delete" @click="clearSigle(index)"></i>
      <el-image
        fit="cover"
        style="width: 100%; height: 100%"
        :src="item.url || item"
        :preview-src-list="showBigList"
        @click="handlePictureCardPreview(item)"
      />
    </div>
    <el-upload
      :class="{ hide: hideUploadEdit }"
      action="#"
      :accept="accept"
      show-file-list
      drag
      list-type="picture-card"
      :file-list="fileList"
      :auto-upload="false"
      :on-change="changeUpload"
    >
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{ file }" class="el-img-box">
        <i
          class="icon del el-icon-delete"
          @click="clearWaiteListSigle(file)"
        ></i>
        <el-image
          class="el-upload-list__item-thumbnail"
          fit="cover"
          :src="file.url"
          :preview-src-list="showBigList"
          @click="handlePictureCardPreview(file)"
        />
        <!-- <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />-->
      </div>
    </el-upload>
    <div class="upload_tip">
      只能上传{{ accept }}文件，且单个文件不超过{{
        maxSize
      }}M，总上传文件大小不超过{{ singleFile }}M
    </div>
    <div class="btn-box">
      <el-button
        size="small"
        type="success"
        :loading="loading"
        @click="submitUpload"
      >
        上传图片
      </el-button>
      <el-button size="small" type="warning" @click="clearList">
        清空图片
      </el-button>
    </div>
  </div>
</template>

<script>
import { uploadImg } from '@/api/common/img'
export default {
  name: 'UploadImg',
  msg: '上传图片公共组件',
  props: {
    fromPage: {
      type: String,
      default: function() {
        return 'pubJob'
      }
    },
    maxLength: {
      //最多上传图片数量
      type: Number,
      default: function() {
        return 9
      }
    },
    maxSize: {
      //单图最大尺寸，默认10M
      type: Number,
      default: function() {
        return 10
      }
    },
    accept: {
      //上传图片支持格式
      type: String,
      default: function() {
        return '.jpg,.png,.gif'
      }
    },
    singleFile: {
      //总文件不超过20M，默认20M
      type: Number,
      default: function() {
        return 20
      }
    },
    imgInfo: {
      // 作业维护-我的发布-编辑页面，传过来的
      type: String,
      default: function() {
        return ''
      }
    },
    imgArray: {
      // 商品活动
      type: Array,
      default: function() {
        return []
      }
    },
    // 支持图片预览
    previewImg: {
      // 商品活动(暂不支持)
      type: Boolean,
      default: function() {
        return true
      }
    }
  },
  data() {
    return {
      loading: false,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList: [],
      imgList: [],
      showBigList: [],
      uploadedImgList: [],
      uploadedImgTotalSize: 0
    }
  },
  computed: {
    hideUploadEdit() {
      return (
        this.maxLength - (this.uploadedImgList.length + this.fileList.length) <=
        0
      )
    }
  },
  watch: {
    fileList(newValue, oldValue) {
      this.getImgList(newValue)
    },
    uploadedImgList(newValue, oldValue) {
      this.getImgList(newValue)
    },
    imgInfo(newValue, oldValue) {
      // imgInfo,作业维护-我的发布-编辑页面，传过来的
      if (newValue) {
        this.uploadedImgList = [...JSON.parse(newValue)]
        this.uploadedImgTotalSize = this.getSize(this.uploadedImgList)
        /*console.log(this.uploadedImgTotalSize)*/
      }
    },
    imgArray(newValue, oldValue) {
      if (newValue.length > 0) {
        this.uploadedImgList = [...newValue]
        this.uploadedImgTotalSize = this.getSize(this.uploadedImgList)
        /*console.log(this.uploadedImgTotalSize)*/
      }
    }
  },
  mounted() {},
  methods: {
    //获取数组中的size总和
    getSize(ary) {
      let sum = 0
      ary.forEach((item) => {
        sum += item.size
      })
      return sum
    },
    checkTotal(size, ary) {
      let total = 0
      let sum = 0
      let uploadedTotal = this.uploadedImgTotalSize / 1024 / 1024
      for (let item of ary) {
        sum += item.size
        total = sum / 1024 / 1024 + uploadedTotal
        if (total > size) {
          return true
        }
      }
      return false
    },
    changeUpload(file, fileList) {
      let totalSize = this.singleFile
      const isLtM = file.size / 1024 / 1024 < this.maxSize
      let totalM = true
      let text = ''
      //校验大小
      if (!isLtM) {
        text += `上传文件大小不能超过 ${this.maxSize}MB!`
        fileList.splice(-1, 1)
      } else if (this.checkTotal(totalSize, fileList)) {
        totalM = false
        text += `总上传文件不能超过 ${totalSize}MB!`
        fileList.splice(-1, 1)
      }
      //校验格式
      let acceptAry = this.accept.split(',')
      let newAry = acceptAry.map((item) => {
        let cur = item.substring(1)
        if (cur === 'jpg') {
          cur = 'jpeg'
        }
        return cur
      })
      let isType = false
      for (let item of newAry) {
        if (file.raw.type === `image/${item}`) {
          isType = true
          break
        }
      }
      if (!isType) {
        text += ` 上传文件格式为 ${this.accept}`
        fileList.splice(-1, 1)
      }
      if (!isType || !isLtM || !totalM) {
        this.$message.error(text)
        return
      }
      this.fileList = [...fileList]

      /*this.loading = true
      let formData = new FormData()
      formData.append('file', file.raw)
      uploadImg(
        formData,
        (response) => {
          this.loading = false
          this.uploadedImgList = this.uploadedImgList.concat(response)
          this.uploadedImgTotalSize += this.getSize(response)
          this.$emit('setImgInfo', this.uploadedImgList)
          this.fileList = []
        },
        (response) => {
          this.loading = false
          this.$message.warning(response.message)
        }
      )*/
    },
    /* 上传图片 */
    submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.error('请选择图片！')
        return
      }
      this.loading = true
      let formData = new FormData()
      this.fileList.forEach((item) => {
        formData.append('file', item.raw)
      })
      uploadImg(
        formData,
        (response) => {
          this.loading = false
          this.uploadedImgList = this.uploadedImgList.concat(response)
          this.uploadedImgTotalSize += this.getSize(response)
          this.$emit('setImgInfo', this.uploadedImgList)
          this.fileList = []
        },
        (response) => {
          this.loading = false
          this.$message.warning(response.message)
        }
      )
    },
    /* 已上传图片列表-删除单个图片 */
    clearSigle(n) {
      this.uploadedImgTotalSize -= this.uploadedImgList[n].size
      this.uploadedImgList.splice(n, 1)
      let str = '[]'
      if (this.uploadedImgList.length > 0) {
        str = JSON.stringify(this.uploadedImgList)
      }
      /* console.log(this.uploadedImgList)*/
      this.$emit('setImgInfo', JSON.parse(str))
    },
    /* 删除 */
    clearList() {
      this.fileList = []
      this.uploadedImgList = []
      this.uploadedImgTotalSize = 0
      this.$emit('setImgInfo', '')
    },
    /* 未上传图片列表-删除单个图片 */
    clearWaiteListSigle(file) {
      let i = this.getWaiteListIndex(file)
      if (i < 0) return
      this.fileList.splice(i, 1)
    },
    /* 获取被点击图片的下标 */
    getWaiteListIndex(file) {
      let n = -1
      this.fileList.forEach((item, index) => {
        if (item.url === file.url) {
          n = index
        }
      })
      return n
    },
    /* 点击预览 */
    handlePictureCardPreview(file) {
      if (this.previewImg) {
        let i = this.getFileIndex(file)
        if (i < 0) return
        let startAry = this.imgList.slice(i)
        let endAry = this.imgList.slice(0, i)
        this.showBigList = startAry.concat(endAry)
      }
    },
    /* 获取被点击图片的下标 */
    getFileIndex(file) {
      let n = -1
      this.imgList.forEach((item, index) => {
        if (item === file.url) {
          n = index
        }
      })
      return n
    },
    /* 获取imgList */
    getImgList(file) {
      // 获取未上传图片地址
      let fileAry = []
      this.fileList.forEach((item) => {
        fileAry.push(item.url)
      })
      // 获取已上传图片地址
      let uploadAry = []
      this.uploadedImgList.forEach((item) => {
        uploadAry.push(item.url)
      })
      // 合并
      this.imgList = uploadAry.concat(fileAry)
    }
  }
}
</script>

<style lang="less">
#uploadImg {
  .hide .el-upload--picture-card {
    display: none;
  }
  .el-upload-dragger {
    width: 100%;
    height: 100%;
    border: 0;
  }
  .img-box {
    position: relative;
    float: left;
    overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda !important;
    border-radius: 6px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 148px !important;
    height: 148px !important;
    margin: 0 8px 8px 0;
  }
  .el-img-box,
  .el-image {
    width: 148px;
    height: 148px;
  }
  .upload_tip {
    clear: both;
    color: #f00;
    font-size: 12px;
    padding-bottom: 5px;
  }
  i.icon {
    position: absolute;
    right: 0;
    top: 0;
    width: 26px;
    height: 22px;
    background: rgba(29, 200, 164, 0.8);
    z-index: 1;
    color: #fff;
    text-align: center;
    line-height: 22px;
    &.del {
      top: auto;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
    }
  }
}
</style>
